package org.wisteria.generator.code.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.wisteria.framework.util.TextUtils;
import org.wisteria.generator.code.mapper.ITableMapper;
import org.wisteria.generator.code.service.ITableService;
import org.wisteria.generator.code.vo.FieldVO;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class TableService implements ITableService {

    @Value("${spring.datasource.db-name}")
    private String schema;

    @Autowired
    private ITableMapper tableMapper;

    @Override
    public List<Map<String, Object>> getTables() {
        return tableMapper.getTables(schema);
    }

    @Override
    public List<FieldVO> getTableColumns(String tableName) {
        List<Map<String, Object>> colums = tableMapper.getTableColumns(schema, tableName);
        if (CollectionUtils.isEmpty(colums)) {
            return null;
        }

        String regex = "_";
        List<FieldVO> fields = new ArrayList<>();
        FieldVO vo = null;
        for (Map<String, Object> col : colums) {
            String name_ = (String)col.get("name");
            String name = "";

            String[] arry = name_.split(regex);
            for (int i = 0; i < arry.length; i++) {
                String arr = arry[i];
                if (i > 0) {
                    arr = TextUtils.firstCharToUpperCase(arr);
                }
                name += arr;
            }

            vo = new FieldVO();
            vo.setName(name);
            vo.setComment(col.get("comment") == null ? null : (String)col.get("comment"));
            vo.setDataType(col.get("dataType") == null ? null : (String)col.get("dataType"));
            fields.add(vo);
        }
        return fields;
    }
}
